﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Common.CommandTrees;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Web.Http;
using WordsOfLoveServer.Models;
using WordsOfLoveServer.Models.Forums;

namespace WordsOfLoveServer.Controllers
{
	public class SentenceController : ApiController
	{
		#region Sentence APIs
		// GET: api/Sentence/GetSentences?word=xxx
		[HttpGet]
		public HttpResponseMessage GetSentences(string word)
		{
			try
			{
				using (var db = new WOLDbContext())
				{
					IQueryable<Sentence> sentences = db.Sentences.Where(x => x.Word == word);
					return new HttpResponseMessage()
					{
						RequestMessage = Request,
						Content = new StringContent(JsonConvert.SerializeObject(sentences.ToList()))
					};
				}
			}
			catch (Exception ex)
			{
				return new HttpResponseMessage(HttpStatusCode.BadRequest)
				{
					Content = new StringContent(ex.Message)
				};
			}
		}

		// POST: api/Sentence/CreateSentence
		[HttpPost]
		public HttpResponseMessage CreateSentence([FromBody] Sentence sentence)
		{
			try
			{
				using (var db = new WOLDbContext())
				{
					db.Sentences.Add(sentence);
					db.SaveChanges();
				}
				return new HttpResponseMessage(HttpStatusCode.Created)
				{
					Content = new StringContent(JsonConvert.SerializeObject(sentence))
				};
			}
			catch (Exception ex)
			{
				return new HttpResponseMessage(HttpStatusCode.BadRequest)
				{
					Content = new StringContent(ex.Message)
				};
			}
		}

		// PUT: api/Sentence/UpdateSentence
		[HttpPut]
		public HttpResponseMessage UpdateSentence([FromBody] Sentence sentence)
		{
			try
			{
				using (var db = new WOLDbContext())
				{
					db.Entry(sentence).State = EntityState.Modified;
					db.SaveChanges();
				}
				return new HttpResponseMessage(HttpStatusCode.OK);
			}
			catch (Exception ex)
			{
				return new HttpResponseMessage(HttpStatusCode.BadRequest)
				{
					Content = new StringContent(ex.Message)
				};
			}
		}

		// DELETE: api/Sentence/DeleteSentence?id=xxx
		[HttpDelete]
		public HttpResponseMessage DeleteSentence(int id)
		{
			try
			{
				using (var db = new WOLDbContext())
				{
					Sentence sentence = db.Sentences.Find(id);
					if (sentence == null)
					{
						return new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("Item doesn't exist.") };
					}
					db.Sentences.Remove(sentence);
					db.SaveChanges();
					return new HttpResponseMessage(HttpStatusCode.OK);
				}
			}
			catch (Exception ex)
			{
				return new HttpResponseMessage(HttpStatusCode.BadRequest)
				{
					Content = new StringContent(ex.Message)
				};
			}
		}

		#endregion
	}
}